package com.yiwei.ydd.activity;

import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.widget.RecyclerView;
import android.text.Spanned;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.allen.library.SuperButton;
import com.bumptech.glide.Glide;
import com.yiwei.ydd.MainActivity;
import com.yiwei.ydd.R;
import com.yiwei.ydd.adapter.PayWayListAdapter;
import com.yiwei.ydd.api.Api;
import com.yiwei.ydd.api.bean.BuyLevelBean;
import com.yiwei.ydd.api.bean.PayPassVerifyBean;
import com.yiwei.ydd.api.bean.PaymentBean;
import com.yiwei.ydd.api.bean.PaymentPayBean;
import com.yiwei.ydd.api.bean.RechargeInstantOrderBean;
import com.yiwei.ydd.api.bean.RechargeTermOrderBean;
import com.yiwei.ydd.api.model.PaymentListModel;
import com.yiwei.ydd.base.BaseActivity;
import com.yiwei.ydd.constant.Const;
import com.yiwei.ydd.constant.UserInfoGlobal;
import com.yiwei.ydd.event.BuyVipUpSuccessEvent;
import com.yiwei.ydd.util.Dialog;
import com.yiwei.ydd.util.MD5;
import com.yiwei.ydd.util.Network;
import com.yiwei.ydd.util.RxLifeUtil;
import com.yiwei.ydd.util.Spans;
import com.yiwei.ydd.util.ToastUtil;
import com.yiwei.ydd.util.UI;
import com.yiwei.ydd.util.Util;
import com.yiwei.ydd.view.SecurityPassDilaog;
import com.yiwei.ydd.view.V19FrameLayout;

import org.greenrobot.eventbus.EventBus;

import java.lang.ref.WeakReference;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;
import cn.beecloud.BCPay;
import cn.beecloud.BeeCloud;
import cn.beecloud.async.BCCallback;
import cn.beecloud.async.BCResult;
import cn.beecloud.entity.BCPayResult;

/**
 * Created by xsooy-pc on 17-12-8.
 */

public class OilcardOrderPayMoneyActivity extends BaseActivity {
    @BindView(R.id.btn_back)
    ImageView btnBack;
    @BindView(R.id.txt_title)
    TextView txtTitle;
    @BindView(R.id.txt_right)
    TextView txtRight;
    @BindView(R.id.layout_title)
    V19FrameLayout layoutTitle;
    @BindView(R.id.txt_need_pay)
    TextView txtNeedPay;
    @BindView(R.id.list)
    RecyclerView list;
    @BindView(R.id.btn_submit)
    SuperButton btnSubmit;
    @BindView(R.id.img_icon)
    ImageView imgIcon;
    @BindView(R.id.txt_name)
    TextView txtName;
    @BindView(R.id.txt_desc)
    TextView txtDesc;
    @BindView(R.id.cb_check)
    ImageView cbCheck;
    @BindView(R.id.layout_total)
    LinearLayout layoutTotal;
    @BindView(R.id.layout_packet)
    LinearLayout layoutPacket;
    @BindView(R.id.layout_other)
    LinearLayout layoutOther;

    private Unbinder unbiner;
    private ProgressDialog progressDialog;
    private PayHandler mHandler;
    private String toastMsg;
    private String selectWays;
    private static final String WX_APP = "WX_APP";
    private static final String ALI_APP = "ALI_APP";
    private static final String ACCOUNT = "BAG";
    private PayWayListAdapter adapter;
    private String payMoney;
    private String orderNo;
    private String account_id;
    private String pay_id;
    private String level_id;
    private String combo_id;
    private String coupon_id;
    private String oilcard_id;
    private boolean is_now_oil = true;
    private String totalMoney;

    //订单类型（1：油卡充值，2：用户升级，3：钱包充值  4：油卡代办）
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_pay_money_vip_order);
        initBar();
        unbiner = ButterKnife.bind(this);
        init();
    }

    private void init() {
        txtTitle.setText("油多多收银台");

        combo_id = getIntent().getStringExtra("combo_id");
        coupon_id = getIntent().getStringExtra("coupon_id");
        totalMoney = getIntent().getStringExtra("money");
        payMoney = getIntent().getStringExtra("sale_money");
        orderNo = getIntent().getStringExtra("order_no");
        oilcard_id = getIntent().getStringExtra("oilcard_id");
//        (String combo_id, String coupon_id, String money, String oilcard_id, String pay_way)
        is_now_oil = getIntent().getBooleanExtra("is_now_oil", true);

        Spanned money = Spans.with(this).font("需支付:", getResources().getDimensionPixelSize(R.dimen.x28), 0xff000000).
                font(payMoney + "元", getResources().getDimensionPixelSize(R.dimen.x28), 0xffFB5E01).
                build();
        btnSubmit.setText("需支付:" + payMoney + "元");
        txtNeedPay.setText(money);
        adapter = new PayWayListAdapter(this);
        adapter.setOnChooseListener(new PayWayListAdapter.OnChooseListener() {
            @Override
            public void onClick(String name, String en_name, String id) {
                selectWays = en_name;
                pay_id = id;
                cbCheck.setImageResource(R.mipmap.img_oil_change_uncheck);
                btnSubmit.setText(name + "支付" + payMoney + "元");
            }
        });
        list.setAdapter(adapter);


        initPay();
        mHandler = new PayHandler(this);

        getPaymentList();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        BCPay.detachWechat();
        bcCallback = null;
        mHandler = null;
        //清理当前的activity引用
        BCPay.clear();
        if (progressDialog != null) {
            progressDialog.dismiss();
            progressDialog = null;
        }
        unbiner.unbind();
        unbiner = null;
    }

    //    ===========================余额支付===========================
    public void getBagPayment(String order_no) {
        if (!Network.checkNetwork(this)) {
            ToastUtil.show(this, "网络连接失败");
            return;
        }


        loadingDialog.show();
        PaymentBean bean = new PaymentBean();
        bean.order_no = order_no;
        Api.api_service.getBagPayment(bean).compose(RxLifeUtil.checkOn(this)).
                doFinally(() -> {
                    try {
                        loadingDialog.dismiss();
                    } catch (NullPointerException e) {

                    }
                }).
                subscribe(result -> {
                    Util.startActivity(OilcardOrderPayMoneyActivity.this, MyOrderActivity.class);
                    EventBus.getDefault().post(new BuyVipUpSuccessEvent());
                    ToastUtil.makeText(this, "支付成功");
                    finish();
                });
    }

    //    ===========================余额支付===========================


    //    ===========================获取支付方式===========================
    public void getPaymentList() {
        if (!Network.checkNetwork(this)) {
            ToastUtil.show(this, "网络连接失败");
            return;
        }
        loadingDialog.show();
        Api.api_service.getPaymentList().compose(RxLifeUtil.checkOn(this)).
                doFinally(() -> {
                    try {
                        loadingDialog.dismiss();
                    } catch (NullPointerException e) {

                    }
                }).
                subscribe(result -> {
                    setPayWay(result.datas);
                });
    }
    //    ===========================获取支付方式===========================


    //    ===========================验证支付密码===========================
    public void getPayPassVerify(String pay_no, String pass) {
        if (!Network.checkNetwork(this)) {
            ToastUtil.show(this, "网络连接失败");
            return;
        }
        loadingDialog.show();
        PayPassVerifyBean bean = new PayPassVerifyBean();
        bean.password = MD5.getMD5str(pass);
        Api.api_service.getPayPassVerify(bean).compose(RxLifeUtil.checkOn(this)).
                doFinally(() -> {
                    try {
                        loadingDialog.dismiss();
                    } catch (NullPointerException e) {

                    }
                }).
                subscribe(result -> {

                    getBagPayment(pay_no);
                });
    }
    //    ===========================验证支付密码===========================

    //    ===========================生成订单===========================
    public void getNowRechargeOrder(String money, String oilcard_id, String pay_way) {
        if (!Network.checkNetwork(this)) {
            ToastUtil.show(this, "网络连接失败");
            return;
        }
        loadingDialog.show();
        RechargeInstantOrderBean bean = new RechargeInstantOrderBean();
        bean.money = money;
        bean.oilcard_id = oilcard_id;
        bean.pay_way = pay_way;
        Api.api_service.getRechargeInstantOrder(bean).compose(RxLifeUtil.checkOn(this)).
                doFinally(() -> {
                    try {
                        loadingDialog.dismiss();
                    } catch (NullPointerException e) {

                    }
                }).
                subscribe(result -> {
                    orderNo = result.datas.order_no;
                    payMoney = result.datas.money;
                    getPaymentPay(orderNo, pay_id);
//                    if (selectWays.equals(ACCOUNT)) {
//                        if (UserInfoGlobal.getIsSetPayPass()) {
//                            new SecurityPassDilaog(this).setOnChooseListener(new SecurityPassDilaog.OnChooseListener() {
//                                @Override
//                                public void onCustomParamChoose(String pass) {
//                                    getPayPassVerify(result.datas.order_no, pass);
//                                }
//                            }).show();
//                        } else {
//                            getBagPayment(result.datas.order_no);
//                        }
//                    } else {
//                        goToPay("支付", Double.valueOf(result.datas.money), result.datas.order_no);
//                    }
                });
    }
    //    ===========================生成订单===========================

    //    ===========================获取分期订单===========================
    public void getRechargeTermOrder(String combo_id, String coupon_id, String money, String oilcard_id, String pay_way) {
        if (!Network.checkNetwork(this)) {
            ToastUtil.show(this, "网络连接失败");
            return;
        }


        loadingDialog.show();
        RechargeTermOrderBean bean = new RechargeTermOrderBean();
        bean.combo_id = combo_id;
        bean.coupon_id = coupon_id;
        bean.money = money;
        bean.oilcard_id = oilcard_id;
        bean.pay_way = pay_way;
        Api.api_service.getRechargeTermOrder(bean).compose(RxLifeUtil.checkOn(this)).
                doFinally(() -> {
                    try {
                        loadingDialog.dismiss();
                    } catch (NullPointerException e) {

                    }
                }).
                subscribe(result -> {
                    orderNo = result.datas.order_no;
                    payMoney = result.datas.money;
                    getPaymentPay(orderNo, pay_id);
//                    if (selectWays.equals(ACCOUNT)) {
//                        getBagPayment(result.datas.order_no);
//                    } else {
//                        goToPay("支付", Double.valueOf(result.datas.money), result.datas.order_no);
//                    }
                });
    }
    //    ===========================获取分期订单===========================

    //    ===========================去支付===========================
    public void getPaymentPay(String order_no, String pay_way) {
        if (!Network.checkNetwork(this)) {
            ToastUtil.show(this, "网络连接失败");
            return;
        }
        loadingDialog.show();
        PaymentPayBean bean = new PaymentPayBean();
        bean.order_no = order_no;
        bean.order_type = "1";
        bean.pay_way = pay_way;
        Api.api_service.getPaymentPay(bean).compose(RxLifeUtil.checkOn(this)).
                doFinally(() -> {
                    try {
                        loadingDialog.dismiss();
                    } catch (NullPointerException e) {

                    }
                }).
                subscribe(result -> {
                    if (selectWays.equals(ACCOUNT)) {
                        if (UserInfoGlobal.getIsSetPayPass()) {
                            new SecurityPassDilaog(this).setOnChooseListener(new SecurityPassDilaog.OnChooseListener() {
                                @Override
                                public void onCustomParamChoose(String pass) {
                                    getPayPassVerify(result.datas.pay_no, pass);
                                }
                            }).show();
                        } else {
                            Dialog.showDefaultDialog(this, "", "为了您的交易安全，请设置交易密码", "", "立即设置", false, new Dialog.DialogDefaultClickListener() {
                                @Override
                                public void confirm() {
                                    Util.startActivity(OilcardOrderPayMoneyActivity.this,TransationSetStepOneActivity.class);
                                }

                                @Override
                                public void cancel() {

                                }
                            });
                        }
                    } else {
                        goToPay(result.datas.name, Double.valueOf(result.datas.money), result.datas.pay_no);
                    }
                });
    }
    //    ===========================去支付===========================


    private void setPayWay(List<PaymentListModel.DatasBean> datas) {
        if (datas != null && datas.size() != 0) {
            for (int i = 0; i < datas.size(); i++) {
                if (datas.get(i).en_name.equals(ACCOUNT)) {
                    txtName.setText(datas.get(i).name);
                    account_id = datas.get(i).id;
                    txtDesc.setText("余额：" + UserInfoGlobal.getBalance());
                    Glide.with(this).load(datas.get(i).icon).into(imgIcon);
                    datas.remove(i);
                    i--;
                }
            }
            adapter.update(datas);
        }
    }

    private void showDialog() {
        if (TextUtils.isEmpty(orderNo)) {
            finish();
            return;
        }
        Dialog.showDefaultDialog(this, "", "订单24小时内会自动取消喔，您确定要离开吗？", "残忍离开", "继续支付", false, new Dialog.DialogDefaultClickListener() {
            @Override
            public void confirm() {

            }

            @Override
            public void cancel() {
                Util.startActivity(OilcardOrderPayMoneyActivity.this, MyOrderActivity.class);
                finish();
            }
        });
    }

    @Override
    public void onBackPressed() {
        showDialog();
    }

    @OnClick({R.id.txt_right, R.id.btn_back, R.id.layout_total, R.id.btn_submit})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.txt_right:
                Util.startActivity(OilcardOrderPayMoneyActivity.this, MyOrderActivity.class);
                break;
            case R.id.btn_back:
                showDialog();
                break;
            case R.id.layout_total:
                selectWays = ACCOUNT;
                pay_id = account_id;
                btnSubmit.setText("钱包支付" + payMoney + "元");
                cbCheck.setImageResource(R.mipmap.img_oil_change_check);
                adapter.clearCheck();
                break;
            case R.id.btn_submit:
                if (TextUtils.isEmpty(selectWays)) {
                    ToastUtil.makeText(this, "请选择支付方式");
                    return;
                }

                if (TextUtils.isEmpty(orderNo)) {
                    if (is_now_oil) {
                        getNowRechargeOrder(totalMoney, oilcard_id, pay_id);
                    } else {
                        getRechargeTermOrder(combo_id, coupon_id, totalMoney, oilcard_id, pay_id);
                    }

                } else {
                    getPaymentPay(orderNo, pay_id);
                }
                break;
        }
    }
//    ===========================获取支付方式===========================

    private void initPay() {
        // 推荐在主Activity或application里的onCreate函数中初始化BeeCloud.
//        if (!Const.IS_DEBUG) {
//            BeeCloud.setSandbox(true);
//
////        测试Appid和secret
//            BeeCloud.setAppIdAndSecret("956fb30c-0579-4469-aa31-64140d64e61c",
//                    "e32e1f0d-d219-4c76-8585-13f953327123");
//        } else {
        BeeCloud.setSandbox(false);
        //     正式网Appid和secret
        BeeCloud.setAppIdAndSecret(Const.BeeCloud.APP_ID,
                Const.BeeCloud.APP_Secret);
//        }


        // 如果用到微信支付，在用到微信支付的Activity的onCreate函数里调用以下函数.
        // 第二个参数需要换成你自己的微信AppID.
//        wx8f9ffda903463ae8
        String initInfo = BCPay.initWechatPay(this, Const.BeeCloud.WECHAT_ID);
        if (initInfo != null) {
            Toast.makeText(this, "微信初始化失败：" + initInfo, Toast.LENGTH_LONG).show();
        }
        progressDialog = new ProgressDialog(this);
        progressDialog.setMessage("处理中，请稍候...");
        progressDialog.setIndeterminate(true);
        progressDialog.setCancelable(true);
    }


    private void goToPay(String title, double money, String bill_no) {
//        Map<String, String> mapOptional = new Gson().fromJson(PayOrderitem.optional, new TypeToken<HashMap<String, String>>() {
//        }.getType());
        Map<String, String> mapOptional = new HashMap<>();
        mapOptional.put("app", Const.getPayOptional());
//        Map<String, String> mapOptional = new HashMap<>();
//        mapOptional.put("disable_pay_channels", "credit_group");
        if (selectWays.equals(ALI_APP)) {
//                    支付宝
            progressDialog.show();
//            BCPay.getInstance(PayTypeActivity.this).reqAliPaymentAsync(
//                    PayOrderitem.title,
//                    PayOrderitem.order_money * 100,
//                    PayOrderitem.notice_sn,
//                    mapOptional,
//                    bcCallback);
            BCPay.getInstance(this).reqAliPaymentAsync(
                    title,
                    (int) (money * 100),
                    bill_no,
                    mapOptional,
                    bcCallback);
        } else if (selectWays.equals(WX_APP)) {
//                    微信
            progressDialog.show();
            //对于微信支付, 手机内存太小会有OutOfResourcesException造成的卡顿, 以致无法完成支付
            //这个是微信自身存在的问题
//            Log.i("dasdasddas", BCPay.isWXAppInstalledAndSupported() + "aa" + BCPay.isWXPaySupported());
            if (BCPay.isWXAppInstalledAndSupported() &&
                    BCPay.isWXPaySupported()) {

//                BCPay.getInstance(this).reqWXPaymentAsync(
//                        PayOrderitem.title,               //订单标题
//                        PayOrderitem.order_money * 100,  //金额
//                        PayOrderitem.notice_sn,  //订单流水号
//                        mapOptional,            //扩展参数(可以null)
//                        bcCallback);            //支付完成后回调入口
                BCPay.getInstance(this).reqWXPaymentAsync(
                        title,               //订单标题
                        (int) (money * 100),  //金额
                        bill_no,  //订单流水号
                        mapOptional,            //扩展参数(可以null)
                        bcCallback);            //支付完成后回调入口

            } else {
                ToastUtil.makeText(this,
                        "您尚未安装微信或者安装的微信版本不支持").show();
                progressDialog.dismiss();
            }
        }
    }


    private static class PayHandler extends Handler {
        WeakReference<OilcardOrderPayMoneyActivity> mActivityReference;

        PayHandler(OilcardOrderPayMoneyActivity activity) {
            mActivityReference = new WeakReference<OilcardOrderPayMoneyActivity>(activity);
        }

        @Override
        public void handleMessage(Message msg) {
            final OilcardOrderPayMoneyActivity activity = mActivityReference.get();
            if (activity != null) {
                switch (msg.what) {
                    case 1:
                        //如果用户手机没有安装银联支付控件,则会提示用户安装
                        AlertDialog.Builder builder = new AlertDialog.Builder(activity);
                        builder.setTitle("提示");
                        builder.setMessage("完成支付需要安装或者升级银联支付控件，是否安装？");

                        builder.setNegativeButton("确定",
                                new DialogInterface.OnClickListener() {
                                    @Override
                                    public void onClick(DialogInterface dialog, int which) {
//                                        UPPayAssistEx.installUPPayPlugin(activity);
                                        dialog.dismiss();
                                    }
                                });

                        builder.setPositiveButton("取消",
                                new DialogInterface.OnClickListener() {

                                    @Override
                                    public void onClick(DialogInterface dialog, int which) {
                                        dialog.dismiss();
                                    }
                                });
                        builder.create().show();
                        break;
                    case 2:
                        Toast.makeText(activity, activity.toastMsg, Toast.LENGTH_SHORT).show();
                        break;
                }
            }
        }
    }


    //支付结果返回入口
    private BCCallback bcCallback = new BCCallback() {
        @Override
        public void done(final BCResult bcResult) {
            final BCPayResult bcPayResult = (BCPayResult) bcResult;
            //此处关闭loading界面
            progressDialog.dismiss();

            //根据你自己的需求处理支付结果
            String result = bcPayResult.getResult();
            /*
              注意！
              所有支付渠道建议以服务端的状态金额为准，此处返回的RESULT_SUCCESS仅仅代表手机端支付成功
            */
            Message msg = mHandler.obtainMessage();
            //单纯的显示支付结果
            msg.what = 2;
            if (result.equals(BCPayResult.RESULT_SUCCESS)) {
                toastMsg = "用户支付成功";
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
//                        getReportResult(money, "1", notice_sn);
                        Util.startActivity(OilcardOrderPayMoneyActivity.this, MyOrderActivity.class);
                        EventBus.getDefault().post(new BuyVipUpSuccessEvent());
                        finish();
                    }
                });
            } else if (result.equals(BCPayResult.RESULT_CANCEL))
                toastMsg = "用户取消支付";
            else if (result.equals(BCPayResult.RESULT_FAIL)) {
                toastMsg = "支付失败, 原因: " + bcPayResult.getErrCode() +
                        " # " + bcPayResult.getErrMsg() +
                        " # " + bcPayResult.getDetailInfo();

                /**
                 * 你发布的项目中不应该出现如下错误，此处由于支付宝政策原因，
                 * 不再提供支付宝支付的测试功能，所以给出提示说明
                 */
                if (bcPayResult.getErrMsg().equals("PAY_FACTOR_NOT_SET") &&
                        bcPayResult.getDetailInfo().startsWith("支付宝参数")) {
                    toastMsg = "支付失败：由于支付宝政策原因，故不再提供支付宝支付的测试功能，给您带来的不便，敬请谅解";
                }

                /**
                 * 以下是正常流程，请按需处理失败信息
                 */

                if (bcPayResult.getErrMsg().equals(BCPayResult.FAIL_PLUGIN_NOT_INSTALLED)) {
                    //银联需要重新安装控件
                    msg.what = 1;
                }
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
//                        getReportResult(money, "2", notice_sn);
                    }
                });

            } else if (result.equals(BCPayResult.RESULT_UNKNOWN)) {
                //可能出现在支付宝8000返回状态
                toastMsg = "订单状态未知";
            } else {
                toastMsg = "invalid return";
            }

            mHandler.sendMessage(msg);

            /*
            if (bcPayResult.getId() != null) {
                //你可以把这个id存到你的订单中，下次直接通过这个id查询订单
                Log.w(TAG, "bill id retrieved : " + bcPayResult.getId());

                //根据ID查询，此处只是演示如何通过id查询订单，并非支付必要部分
                getBillInfoByID(bcPayResult.getId());
            }
            */
        }
    };
}
